<template>
  <div>
    <el-row>
      <el-col :span="4" :offset="10">
        <el-form ref="loginForm"
                 :model="loginForm"
                 style="margin-top: 120px;"
                 :rules="loginFormRules"
                 label-position="top">
          <el-header>
            <h2 class="title">Admin</h2>
          </el-header>
          <el-main>
            <el-form-item label="手机号码" prop="username">
              <el-input placeholder="手机号码" v-model="loginForm.username"></el-input>
            </el-form-item>
            <p style="margin-top: 20px;"/>

            <el-form-item label="密码" prop="password">
              <el-input placeholder="密码" v-model="loginForm.password" type="password"></el-input>
            </el-form-item>
            <p style="margin-top: 20px;"/>

            <el-button type="primary" style="width: 100%;" @click="login">登录</el-button>
          </el-main>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>


export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        username: "17585367620",
        password: ""
      },
      loginFormRules: {
        username:[
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: this.checkTelephone, trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 16,message: '密码长度在6-16之间', trigger: 'blur'},
        ]
      }

    }
  },
  methods:{
    checkTelephone(rule, value, callback) {
      let reg=/^1[3,4,5,7,8][0-9]{9}$/;
        if (!reg.test(value)) {
          callback(new Error("请输入正确的手机号"))
        } else {
          callback()
        }
    },
    login(){
      this.$refs.loginForm.validate( async v => {
        let params = {
          username: this.loginForm.username,
          password: this.loginForm.password
        }
        if (v) {
          //  send  request
            this.$flyLoading.start()
          const {data: res} = await this.$http.post('cms/login', params);
          const token = res.token;
          const user = res.user;
          if(user === undefined){
              this.$flyLoading.end()
            this.$message.error(res.message);
          }else{
            this.$auth.setUserAndToken(user, token);
            this.$flyLoading.end()
            this.$message.success('登录成功');
            this.$router.push('/home');
          }
        }

      })
    }

}

}
</script>

<style scoped lang="scss">
.title{
  text-align: center;
}
#body{
  background: #eee;
}
</style>
